package com.xujianlong.day04;

import com.xujianlong.bean.UserBehavior;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;
import java.util.HashSet;
import java.util.stream.Stream;

public class Flink03_Project_PV_Process {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        env.setRuntimeMode(RuntimeExecutionMode.STREAMING);

        DataStreamSource<String> dataStreamSource = env.readTextFile("input/UserBehavior.csv");

        SingleOutputStreamOperator<Tuple2<String, Long>> uvToCount = dataStreamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                //a.将数据转为JavaBean
                String[] split = s.split(",");
                UserBehavior userBehavior = new UserBehavior(
                        Long.parseLong(split[0]),
                        Long.parseLong(split[1]),
                        Integer.parseInt(split[2]),
                        split[3],
                        Long.parseLong(split[4])
                );

                if ("pv".equals(userBehavior.getBehavior())) {
                    collector.collect(Tuple2.of("uv", userBehavior.getUserId()));
                }
            }
        });
        KeyedStream<Tuple2<String, Long>, Tuple> keyedDS = uvToCount.keyBy(0);
        keyedDS.process(new ProcessFunction<Tuple2<String, Long>, Tuple2<String,Integer>>() {
            HashSet<Tuple2<String,Long>> uvHashSet = new HashSet<>();
            @Override
            public void processElement(Tuple2<String, Long> value, Context context, Collector<Tuple2<String, Integer>> collector) throws Exception {
                uvHashSet.add(value);
                int count=uvHashSet.size();
                collector.collect(Tuple2.of("uv",count));
            }
        }).print();

        env.execute();
    }
}
